package classpath

import (
	"archive/zip"
	"fmt"
	"io"
	"path/filepath"
)

type ZipEntry struct {
	absPath string
}

func newZipEntry(path string) *ZipEntry {
	abs, err := filepath.Abs(path)
	if err != nil {
		panic(err)
	}

	return &ZipEntry{abs}
}

func (e *ZipEntry) readClass(className string) ([]byte, Entry, error) {
	reader, err := zip.OpenReader(e.absPath)
	if err != nil {
		return nil, nil, err
	}
	defer reader.Close()
	for _, file := range reader.File {
		if file.Name == className {
			fileReader, err := file.Open()
			if err != nil {
				return nil, nil, err
			}
			defer fileReader.Close()
			data, err := io.ReadAll(fileReader)
			if err != nil {
				return nil, nil, err
			}
			return data, e, nil
		}
	}
	return nil, nil, fmt.Errorf("class %s not found", className)
}

func (e *ZipEntry) String() string {
	return e.absPath
}
